<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable size="small">
          <el-option
            v-for="project in projects"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="未开始" value="NOT_STARTED"/>
          <el-option label="进行中" value="IN_PROGRESS"/>
          <el-option label="阻塞" value="BLOCKED"/>
          <el-option label="已完成" value="COMPLETED"/>
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable size="small">
          <el-option label="低" value="LOW"/>
          <el-option label="中" value="MEDIUM"/>
          <el-option label="高" value="HIGH"/>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="ownerId">
        <el-select v-model="queryParams.ownerId" placeholder="请选择负责人" clearable size="small">
          <el-option
            v-for="user in users"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:task:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:task:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:task:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="任务ID" align="center" prop="id"/>
      <el-table-column label="任务名称" align="center" prop="name"/>
      <el-table-column label="所属项目" align="center" prop="projectId">
        <template slot-scope="scope">
          <span>{{ getProjectName(scope.row.projectId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="ownerId">
        <template slot-scope="scope">
          <span>{{ getUserName(scope.row.ownerId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template slot-scope="scope">
          <el-tag :type="getPriorityType(scope.row.priority)">
            {{ getPriorityLabel(scope.row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进度" align="center" prop="progress">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.progress"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:task:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:task:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="父任务" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父任务">
            <el-option label="无" value=""/>
            <el-option
              v-for="task in tasks"
              :key="task.id"
              :label="task.name"
              :value="task.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入任务描述"/>
        </el-form-item>
        <el-form-item label="负责人" prop="ownerId">
          <el-select v-model="form.ownerId" placeholder="请选择负责人">
            <el-option
              v-for="user in users"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option label="低" value="LOW"/>
            <el-option label="中" value="MEDIUM"/>
            <el-option label="高" value="HIGH"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="未开始" value="NOT_STARTED"/>
            <el-option label="进行中" value="IN_PROGRESS"/>
            <el-option label="阻塞" value="BLOCKED"/>
            <el-option label="已完成" value="COMPLETED"/>
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择计划开始日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="计划结束" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择计划结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="实际开始" prop="actualStartDate">
          <el-date-picker
            v-model="form.actualStartDate"
            type="date"
            placeholder="选择实际开始日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="实际结束" prop="actualEndDate">
          <el-date-picker
            v-model="form.actualEndDate"
            type="date"
            placeholder="选择实际结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="预估工时" prop="estimatedHours">
          <el-input-number v-model="form.estimatedHours" :precision="1" :step="0.5"/>
        </el-form-item>
        <el-form-item label="实际工时" prop="actualHours">
          <el-input-number v-model="form.actualHours" :precision="1" :step="0.5"/>
        </el-form-item>
        <el-form-item label="进度" prop="progress">
          <el-slider v-model="form.progress" :min="0" :max="100"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listTask, getTask, delTask, addTask, updateTask} from "@/api/hanyun/task";
import {getUserList, listProjects} from "@/api/hanyun/project";

export default {
  name: "Task",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务表格数据
      taskList: [],
      // 项目列表
      projects: [],
      // 用户列表
      users: [],
      // 任务列表(用于选择父任务)
      tasks: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        status: null,
        priority: null,
        ownerId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "任务名称不能为空", trigger: "blur"}
        ],
        projectId: [
          {required: true, message: "所属项目不能为空", trigger: "change"}
        ],
        ownerId: [
          {required: true, message: "负责人不能为空", trigger: "change"}
        ],
        priority: [
          {required: true, message: "优先级不能为空", trigger: "change"}
        ],
        status: [
          {required: true, message: "状态不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getProjects();
    this.getUsers();
    this.getTasks();
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取项目列表 */
    getProjects() {
      // TODO: 调用获取项目列表接口
      listProjects({}).then(response => {
        this.projects = response.rows;
      });
    },
    /** 获取用户列表 */
    getUsers() {
      // TODO: 调用获取用户列表接口
      getUserList().then(response => {
        this.users = response.rows;
      });
    },
    /** 获取任务列表 */
    getTasks() {
      // TODO: 调用获取任务列表接口
      this.tasks = [];
      listTask({}).then(response => {
        this.tasks = response.rows;
      })
    },
    /** 获取项目名称 */
    getProjectName(projectId) {
      const project = this.projects.find(p => p.id === projectId);
      return project ? project.name : projectId;
    },
    /** 获取用户名称 */
    getUserName(userId) {
      const user = this.users.find(u => u.userId === userId);
      return user ? user.userName : userId;
    },
    /** 获取优先级标签 */
    getPriorityLabel(priority) {
      const map = {
        LOW: "低",
        MEDIUM: "中",
        HIGH: "高"
      };
      return map[priority] || priority;
    },
    /** 获取优先级类型 */
    getPriorityType(priority) {
      const map = {
        LOW: "info",
        MEDIUM: "warning",
        HIGH: "danger"
      };
      return map[priority] || "info";
    },
    /** 获取状态标签 */
    getStatusLabel(status) {
      const map = {
        NOT_STARTED: "未开始",
        IN_PROGRESS: "进行中",
        BLOCKED: "阻塞",
        COMPLETED: "已完成"
      };
      return map[status] || status;
    },
    /** 获取状态类型 */
    getStatusType(status) {
      const map = {
        NOT_STARTED: "info",
        IN_PROGRESS: "primary",
        BLOCKED: "warning",
        COMPLETED: "success"
      };
      return map[status] || "info";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        parentId: null,
        name: null,
        description: null,
        ownerId: null,
        priority: "MEDIUM",
        status: "NOT_STARTED",
        startDate: null,
        endDate: null,
        actualStartDate: null,
        actualEndDate: null,
        estimatedHours: null,
        actualHours: null,
        progress: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除任务编号为"' + ids + '"的数据项？').then(function () {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
